by: Francisco Ingham and Jeremy Howard. Inspired by Adrian Rosebrock
In this tutorial we will see how to easily create an image dataset through Google Images. Note: You will have to repeat these steps for any new category you want to Google (e.g once for dogs and once for cats).
Go to Google Images and search for the images you are interested in. The more specific you are in your Google Search, the better the results and the less manual pruning you will have to do.
Scroll down until you see a button that says 'Show more results'. All the images you scrolled past are now available to download. To get more, click on the button. Then continue scrolling until you cannot scroll anymore. The maximum number of images Google Images shows is 700.
It is a good idea to put things you want to exclude into the search query, for instance if you are searching for the Eurasian wolf, "canis lupus lupus", it might be a good idea to exclude other variants:
"canis lupus lupus" -dog -arctos -familiaris -baileyi -occidentalis
You can also limit your results to show only photos by clicking on Tools and selecting Photos from the Type dropdown.
Now you must run some Javascript code in your browser which will save the URLs of all the images you want for you dataset.
Press CtrlShiftJ in Windows/Linux and CmdOptJ in Mac, and a small window the javascript 'Console' will appear. That is where you will paste the JavaScript commands.
You will need to get the urls of each of the images. You can do this by running the following commands:
urls = Array.from(document.querySelectorAll('.rg_di .rg_meta')).map(el=>JSON.parse(el.textContent).ou);
window.open('data:text/csv;charset=utf-8,' + escape(urls.join('\n')));
from fastai import *
from fastai.vision import *
Choose an appropriate name for your labeled images. You can run these steps multiple times to grab different labels.
folder = 'panda'
file = 'urls_panda.txt'
folder = 'koala'
file = 'urls_koala.txt'
folder = 'kangaroo'
file = 'urls_kangaroo.txt'
path = Path('data/animals')
dest = path/folder
dest.mkdir(parents=True, exist_ok=True)
Finally, upload your urls file. You just need to press Upload in your working directory and select your file, then click 'upload' on the right.

folder, file, path, dest
Now you will need to download you images from their respective urls.
fast.ai has a function that allows you to do just that. You just have to specify the urls filename and the destination folder and this function will download and save all images than can be opened. If they have some problem in being opened, they will not be saved.
Let's download our images! Notice you can choose a maximum number of images to be downloaded. In this case we will not download all the urls.
download_images(path/folder/file, dest, max_pics=300)
Good! Let's take a look at some of our pictures then.
classes = ['kangaroo','panda','koala']
# This function will delete the txt files for each animal, leaving me with just images within each animal folder
for c in classes:
print(c)
verify_images(path/c, delete=True, max_workers=8)
doc(verify_images)
np.random.seed(42)
data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.2, ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)
data.classes
data.show_batch(rows=4, figsize=(7,8))
data.classes, data.c, len(data.train_ds), len(data.valid_ds)
learn = create_cnn(data, models.resnet34, metrics=error_rate)
learn.fit_one_cycle(4)
learn.save('stage-1')
learn.unfreeze()
learn.lr_find()
learn.recorder.plot()
learn.fit_one_cycle(2, max_lr=slice(3e-5,3e-4))
learn.save('stage-2')
learn.load('stage-2')
interp = ClassificationInterpretation.from_learner(learn)
interp.plot_confusion_matrix()
interp.plot_top_losses(6)
interp.most_confused()
Some of our top losses aren't due to bad performance by our model. There are images in our data set that shouldn't be.
Using the FileDeleter widget from fastai.widgets we can prune our top losses, removing photos that don't belong.
First we need to get the file paths from our top_losses. Here's a handy function that pulls out all our top_losses:
from fastai.widgets import *
losses,idxs = interp.top_losses()
top_loss_paths = data.valid_ds.x[idxs]
Now we can pass in these paths to our widget.
fd = FileDeleter(file_paths=top_loss_paths)
Flag photos for deletion by clicking 'Delete'. Then click 'Confirm' to delete flagged photos and keep the rest in that row. The File_Deleter will show you a new row of images until there are no more to show. In this case, the widget will show you images until there are none left from top_losses.
data.classes
You probably want to use CPU for inference, except at massive scale (and you almost certainly don't need to train in real-time). If you don't have a GPU that happens automatically. You can test your model on CPU like so:
# fastai.defaults.device = torch.device('cpu')
img = open_image(path/'kangaroo'/'00000021.jpg')
img